package com.hbnu.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.core.util.PageUtil;
import com.hbnu.system.mapper.Meeting_joinMapper;
import com.hbnu.system.model.dto.CheckBackDTO;
import com.hbnu.system.model.dto.SearchPageDTO;
import com.hbnu.system.model.dto.UserDTO;
import com.hbnu.system.model.entity.Audit;
import com.hbnu.system.model.entity.Meeting_join;
import com.hbnu.system.model.entity.User;
import com.hbnu.system.model.vo.InfoVO;
import com.hbnu.system.service.*;
import com.hbnu.system.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-05-16
 */
@Service
public class Meeting_joinServiceImpl extends ServiceImpl<Meeting_joinMapper, Meeting_join> implements IMeeting_joinService {

    @Autowired
    IMeeting_joinService iMeeting_joinService;
    @Autowired
    IUserService iUserService;
    @Autowired
    private IDeptService iDeptService;
    @Autowired
    IAuthorityService iAuthorityService;
    @Autowired
    AuditService auditService;
    @Override
    public boolean addmeetjoin(Meeting_join meetingjoin) {
        if(StrUtil.isEmpty(meetingjoin.getClassifi()) || StrUtil.isBlank(meetingjoin.getClassifi())){
            throw new BaseException("请输入统计分类");
        }
        if(StrUtil.isEmpty(meetingjoin.getMeetingname()) || StrUtil.isBlank(meetingjoin.getMeetingname())){
            throw new BaseException("请输入会议名称");
        }
        if(StrUtil.isEmpty(meetingjoin.getDept()) || StrUtil.isBlank(meetingjoin.getDept())){
            throw new BaseException("请输入所属院系");
        }
        if(StrUtil.isEmpty(meetingjoin.getDisciplineclassifi()) || StrUtil.isBlank(meetingjoin.getDisciplineclassifi())){
            throw new BaseException("请输入学科分类");
        }
        if(StrUtil.isEmpty(meetingjoin.getMeetingcate()) || StrUtil.isBlank(meetingjoin.getMeetingcate())){
            throw new BaseException("请输入会议类型");
        }
        if(StrUtil.isEmpty(meetingjoin.getMeetingplace()) || StrUtil.isBlank(meetingjoin.getMeetingplace())){
            throw new BaseException("请输入参会地址");
        }
        Meeting_join meeting_join1 = super.getOne(Wrappers.lambdaQuery(Meeting_join.class).eq(Meeting_join::getMeetingname,meetingjoin.getMeetingname()));
        if(Objects.nonNull(meeting_join1)){
            throw new BaseException("参与会议名重复");
        }

        meetingjoin.setStatus("草稿");
        if(Objects.isNull(meetingjoin.getEntereddate())){
            meetingjoin.setEntereddate(LocalDate.now());
        }

        return baseMapper.insert(meetingjoin)==1;
    }

    @Override
    public boolean deletemeetjoin(String PID) {
        Meeting_join one = super.getOne(Wrappers.lambdaQuery(Meeting_join.class)
                .eq(Meeting_join::getJoinMeetingID, PID));
        if (Objects.isNull(one)){
            throw new BaseException("参与会议编号有误!");
        }
        return baseMapper.deleteById(PID) == 1;
    }

    @Override
    public boolean updatemeetjoin(Meeting_join meetingjoin) {
        if(StrUtil.isEmpty(meetingjoin.getClassifi()) || StrUtil.isBlank(meetingjoin.getClassifi())){
            throw new BaseException("请输入统计分类");
        }
        if(StrUtil.isEmpty(meetingjoin.getMeetingname()) || StrUtil.isBlank(meetingjoin.getMeetingname())){
            throw new BaseException("请输入会议名称");
        }
        if(StrUtil.isEmpty(meetingjoin.getDept()) || StrUtil.isBlank(meetingjoin.getDept())){
            throw new BaseException("请输入所属院系");
        }
        if(StrUtil.isEmpty(meetingjoin.getDisciplineclassifi()) || StrUtil.isBlank(meetingjoin.getDisciplineclassifi())){
            throw new BaseException("请输入学科分类");
        }
        if(StrUtil.isEmpty(meetingjoin.getMeetingcate()) || StrUtil.isBlank(meetingjoin.getMeetingcate())){
            throw new BaseException("请输入会议类型");
        }
        if(StrUtil.isEmpty(meetingjoin.getMeetingplace()) || StrUtil.isBlank(meetingjoin.getMeetingplace())){
            throw new BaseException("请输入参会地址");
        }
        return baseMapper.updateById(meetingjoin)==1;
    }

    @Override
    public Meeting_join getmeetjoinbyid(String mjID) {
        Meeting_join one = super.getOne(Wrappers.lambdaQuery(Meeting_join.class)
                .eq(Meeting_join::getJoinMeetingID, mjID));
        if(Objects.isNull(one)){
            throw new BaseException("参与会议编号异常!未查找到该参与会议");
        }
        return one;
    }

    @Override
    public boolean checkmeetjoinName(String name) {
        Meeting_join one = super.getOne(Wrappers.lambdaQuery(Meeting_join.class)
                .eq(Meeting_join::getMeetingname, name));
        if(Objects.nonNull(one)){
            throw new BaseException("该参与会议名称已存在!");
        }
        return true;
    }

    @Override
    public IPage<Meeting_join> pageCondition(SearchPageDTO searchPageDTO) {
        IPage<Meeting_join> mh = PageUtil.getPage(searchPageDTO.getPageNum(), searchPageDTO.getPageSize());
        LambdaQueryWrapper<Meeting_join> wrapper = Wrappers.lambdaQuery(Meeting_join.class);
        IPage<Meeting_join> meethIPage = baseMapper.selectPage(mh, wrapper);
//        IPage<PaperVO> taskVOIPage = iBeanService.copyPageProperties(paperIPage, PaperVO.class);
        List<Meeting_join> records = meethIPage.getRecords();
        List<Meeting_join> meethoS = new ArrayList<>();

        int count = 1;
        int start = searchPageDTO.getPageSize() * (searchPageDTO.getPageNum()-1)+1;
        int end = searchPageDTO.getPageNum() * searchPageDTO.getPageSize();
//        records.forEach(record->{
//            if (count >= start && count <= end){
//                PaperS.add(this.getPaper(record.getPaperID()));
//            }
//        });
        Collections.reverse(records);
        for (Meeting_join record:records) {
            if (count >= start && count <= end){
                meethoS.add(this.getmeetjoinbyid(record.getJoinMeetingID()));
            }
            count += 1;
        }


//        Collections.reverse(meethoS);
        meethIPage.setRecords(meethoS);
        meethIPage.setTotal(records.size());
        return meethIPage;
    }

    @Override
    public Boolean schoolCheckPass(String token,String PID) {
        Meeting_join mt = iMeeting_joinService.getmeetjoinbyid(PID);
        if (Objects.isNull(mt)){
            throw new BaseException("该参与会议编号有误!");
        }
        if(!mt.getStatus().equals("待校级审核")){
            throw new BaseException("该参与会议状态不处于该环节!");
        }
        mt.setStatus("审核通过");

        InfoVO info = JwtUtils.getInfo(token);
        String[] strings = new String[1];
        strings[0] = iAuthorityService.getById(info.getRoles()[0]).getText();
        User user = iUserService.getById(info.getUid());
        String role = strings[0];
        String name = user.getName();

        Audit audit = new Audit();
        audit.setSynthesisID(PID);
        audit.setAuditerRole(role);
        audit.setAuditerName(name);
        audit.setStatusChange("参与会议待校级审核->校级审核通过");
        audit.setAuditOpinion("通过");
        audit.setAuditerTime(LocalDateTime.now());
        auditService.addAudit(audit);
        return baseMapper.updateById(mt) == 1;
    }

    @Override
    public Boolean schoolCheckBack(String token,CheckBackDTO checkBackDTO) {
        String id = checkBackDTO.getID();
        Meeting_join mt = iMeeting_joinService.getmeetjoinbyid(id);
        if (Objects.isNull(mt)){
            throw new BaseException("该参与会议编号有误!");
        }
        if(!mt.getStatus().equals("待校级审核")){
            throw new BaseException("该参与会议状态不处于该环节!");
        }
        mt.setStatus("校级审核退回");
        mt.setReason(checkBackDTO.getReason());

        InfoVO info = JwtUtils.getInfo(token);
        String[] strings = new String[1];
        strings[0] = iAuthorityService.getById(info.getRoles()[0]).getText();
        User user = iUserService.getById(info.getUid());
        String role = strings[0];
        String name = user.getName();

        Audit audit = new Audit();
        audit.setSynthesisID(checkBackDTO.getID());
        audit.setAuditOpinion(checkBackDTO.getReason());
        audit.setAuditerRole(role);
        audit.setAuditerName(name);
        audit.setStatusChange("参与会议待校级审核->被校级退回");
        audit.setAuditerTime(LocalDateTime.now());
        auditService.addAudit(audit);
        return baseMapper.updateById(mt) == 1;
    }

    @Override
    public Boolean ReCommitMeetingjoin(String id) {
        Meeting_join meetingjoin = super.getOne(Wrappers.lambdaQuery(Meeting_join.class)
                .eq(Meeting_join::getJoinMeetingID,id));
        if(StrUtil.isEmpty(meetingjoin.getClassifi()) || StrUtil.isBlank(meetingjoin.getClassifi())){
            throw new BaseException("请输入统计分类");
        }
        if(StrUtil.isEmpty(meetingjoin.getMeetingname()) || StrUtil.isBlank(meetingjoin.getMeetingname())){
            throw new BaseException("请输入会议名称");
        }
        if(StrUtil.isEmpty(meetingjoin.getDept()) || StrUtil.isBlank(meetingjoin.getDept())){
            throw new BaseException("请输入所属院系");
        }
        if(StrUtil.isEmpty(meetingjoin.getDisciplineclassifi()) || StrUtil.isBlank(meetingjoin.getDisciplineclassifi())){
            throw new BaseException("请输入学科分类");
        }
        if(StrUtil.isEmpty(meetingjoin.getMeetingcate()) || StrUtil.isBlank(meetingjoin.getMeetingcate())){
            throw new BaseException("请输入会议类型");
        }
        if(StrUtil.isEmpty(meetingjoin.getMeetingplace()) || StrUtil.isBlank(meetingjoin.getMeetingplace())){
            throw new BaseException("请输入参会地址");
        }
        meetingjoin.setStatus("待校级审核");
        meetingjoin.setReason("");
        return baseMapper.updateById(meetingjoin)==1;
    }

    @Override
    public IPage<Meeting_join> userGetRelatejoinmeeting(UserDTO userDTO) {
        if(Objects.isNull(iUserService.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getName,userDTO.getName())))){
            IPage<Meeting_join> page = PageUtil.getPage(userDTO.getPageNum(), userDTO.getPageSize());
            return page;
        }
        IPage<Meeting_join> page = PageUtil.getPage(userDTO.getPageNum(), userDTO.getPageSize());
        LambdaQueryWrapper<Meeting_join> wrapper = Wrappers.lambdaQuery(Meeting_join.class)
                .eq(Meeting_join::getEntered, userDTO.getName());
        // 检查 projectName 是否为空或空白
        if (StrUtil.isNotBlank(userDTO.getSearch())) {
            // 如果 projectName 不为空或空白，添加模糊查询条件
            wrapper.like(Meeting_join::getMeetingname, userDTO.getSearch());
        }
        IPage<Meeting_join> meetingIPage = baseMapper.selectPage(page, wrapper);
        List<Meeting_join> records = meetingIPage.getRecords();
//        IPage<PaperVO> paperVOIPage = iBeanService.copyPageProperties(paperIPage, PaperVO.class);
        ArrayList<Meeting_join> meetingList = new ArrayList<>();

        //对分页的设置
        int count = 1;
        int start = userDTO.getPageSize() * (userDTO.getPageNum()-1)+1;
        int end = userDTO.getPageNum() * userDTO.getPageSize();
        Collections.reverse(records);
        for (Meeting_join record:records) {
            if (count >= start && count <= end){
                meetingList.add(this.getmeetjoinbyid(record.getJoinMeetingID()));
//                paperList.add(this.getPaperVO(record.getPaperID()));
            }
            count += 1;
        }

//        Collections.reverse(meetingList);
        meetingIPage.setRecords(meetingList);
        meetingIPage.setTotal(records.size());

        return meetingIPage;
    }

    @Override
    public IPage<Meeting_join> schoolUserGetjoinmeeting(UserDTO userDTO) {
        User one = iUserService.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getName, userDTO.getName()));
        String dept = one.getDept();
        String deptName = iDeptService.getById(dept).getDeptName();
        String role = one.getRole();
        if(!role.equals("19190251173")){
            throw new BaseException("该用户权限不为校级审核员!");
        }
        IPage<Meeting_join> page = PageUtil.getPage(userDTO.getPageNum(), userDTO.getPageSize());
        LambdaQueryWrapper<Meeting_join> wrapper = Wrappers.lambdaQuery(Meeting_join.class)
                .and(wrapper1 -> wrapper1.eq(Meeting_join::getStatus,"待校级审核"));
        // 检查 projectName 是否为空或空白
        if (StrUtil.isNotBlank(userDTO.getSearch())) {
            // 如果 projectName 不为空或空白，添加模糊查询条件
            wrapper.like(Meeting_join::getMeetingname, userDTO.getSearch());
        }
        IPage<Meeting_join> meetingHostIPage = baseMapper.selectPage(page, wrapper);
        List<Meeting_join> records = meetingHostIPage.getRecords();
//        IPage<PaperVO> paperVOIPage = iBeanService.copyPageProperties(paperIPage, PaperVO.class);
        ArrayList<Meeting_join> meethostList = new ArrayList<>();

        //对分页的设置
        int count = 1;
        int start = userDTO.getPageSize() * (userDTO.getPageNum()-1)+1;
        int end = userDTO.getPageNum() * userDTO.getPageSize();
        Collections.reverse(records);
        for (Meeting_join record:records) {
            if (count >= start && count <= end){
//                this.getPaper(record.getPaperID())
                meethostList.add(this.getmeetjoinbyid(record.getJoinMeetingID()));
            }
            count += 1;
        }

//        Collections.reverse(meethostList);
        meetingHostIPage.setRecords(meethostList);
        meetingHostIPage.setTotal(records.size());

        return meetingHostIPage;
    }
}
